package unibratec.projeto;

import java.util.List;

import unibratec.projeto.model.Evento;
import unibratec.projeto.model.EventoDAO;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class ListaEventosActivity extends ListActivity{

	EventoDAO repo;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		repo = new EventoDAO(this);
        registerForContextMenu(getListView());
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		atualizaLista();
	}
	
	private void atualizaLista() {
		List<Evento> eventos = repo.listar();
		
		ArrayAdapter<Evento> adapter = new ArrayAdapter<Evento>(
				this, android.R.layout.simple_list_item_1, eventos);
		setListAdapter(adapter);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		Evento evento = (Evento)l.getAdapter().getItem(position);
		
		Intent it = new Intent(this, TelaCadastroEventoActivity.class);
		//it.putExtra("eventoSelecionado", evento);
		startActivity(it);
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 0, "Cadastrar").setIcon(android.R.drawable.ic_menu_add);
		menu.add(0, 2, 0, "Sair").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, 3, 0, "Excluir");
	}
	
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			startActivity(new Intent(this, TelaCadastroEventoActivity.class));
			break;

		case 2:
			finish();
			break;
			
		case 3:
			AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)
				item.getMenuInfo();
			
			Evento evento = (Evento)getListAdapter().getItem(menuInfo.position);
			
			repo.excluir(evento);
			
			atualizaLista();
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}
}
